package microservices.spring_cloud_server.rest;

import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import microservices.spring_cloud_server.dao.UserDao;
import microservices.spring_cloud_server.vo.UserVO;

@RestController
public class LoginService {
	@Autowired
	private UserDao userDao;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(@RequestBody final UserVO userVO) throws ServletException {
		String password = userDao.getPassWord(userVO);
		List<String> permission = userDao.getPermissionByUser(userVO);
		if (userVO.getUserName() == null || password == null || !password.equals(userVO.getUserPassword())) {
			return "error";
		}
		return Jwts.builder().setSubject(userVO.getUserName()).claim("permission", permission).setIssuedAt(new Date())
				.signWith(SignatureAlgorithm.HS256, "secretkey").compact();
	}

}
